package edu.xmut.yuepai.common.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import edu.xmut.yuepai.common.constant.AuthConstants;
import edu.xmut.yuepai.common.utils.UserContext;
import feign.RequestInterceptor;
import feign.codec.Encoder;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

@Configuration
public class FeignClientConfig {

    @Resource
    private FastJsonHttpMessageConverter fastJsonHttpMessageConverter;

    @Bean
    public Encoder feignEncoder() {
        return new SpringEncoder(feignHttpMessageConverter());
    }

    private ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
        final HttpMessageConverters httpMessageConverters = new HttpMessageConverters(fastJsonHttpMessageConverter);
        return () -> httpMessageConverters;
    }

    @Bean
    public RequestInterceptor userIDrequestInterceptor() {
        return template -> {
            Long userId = UserContext.getUserId();
            if (Objects.nonNull(userId)) {
                template.header(AuthConstants.USER_ID_HEADER, userId.toString());
            }
        };
    }

}
